package com.ajmd.onlineexam.service;

import com.ajmd.onlineexam.entity.FolderPO;
import com.ajmd.onlineexam.entity.QuestionBankPO;
import com.ajmd.onlineexam.entity.QuestionPO;
import com.ajmd.onlineexam.entity.SearchParam;
import com.ajmd.onlineexam.enumeration.StaticFinalValue;
import com.ajmd.onlineexam.mapper.FolderMapper;
import com.ajmd.onlineexam.mapper.QuestionBankMapper;
import com.ajmd.onlineexam.mapper.QuestionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author ajmd
 * @since 2023/4/4 19:53
 */
@Service
public class QuestionBankService {
    @Resource
    private QuestionBankMapper questionBankMapper;
    @Resource
    private FolderMapper folderMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private FolderService folderService;

    public QuestionBankPO selectById(String id){
        return questionBankMapper.selectById(id);
    }

//    @Transactional
    public int addQuestionBank(QuestionBankPO questionBankPO){
        UUID uuid = UUID.randomUUID();
        questionBankPO.setId(uuid.toString());
        return questionBankMapper.insert(questionBankPO);
    }



    public Page<QuestionBankPO> findByFolder(String belongFolderId, String account, SearchParam searchParam, Integer userType,
                                             Integer folderRange, Integer currentPage, Integer pageSize){
//        MPJLambdaWrapper<QuestionBankPO> queryWrapper = new MPJLambdaWrapper<>();
        LambdaQueryWrapper<QuestionBankPO> queryWrapper = new LambdaQueryWrapper<>();
        //如果是教师还需要做以下限制，否则是管理员不做限制（查看所有）
        if(StaticFinalValue.TEACHER.equals(userType)){
            if(StaticFinalValue.CLICK_ONLY_MY_FOLDERS.equals(folderRange)){
                //仅查看自己创建的
                Set<String> folderIds = folderService.getFolderIds(account);
                queryWrapper.eq(QuestionBankPO::getCreatePerson,account)
                        .in(QuestionBankPO::getBelongFolderId,folderIds);

//                queryWrapper.selectAll(QuestionBankPO.class)
//                        .innerJoin(FolderPO.class,FolderPO::getId,QuestionBankPO::getBelongFolderId)
//                        .eq(FolderPO::getCreatePerson,account)
//                        .eq(QuestionBankPO::getCreatePerson,account)
//                        .eq(FolderPO::getChainCreatedBySamePerson,StaticFinalValue.CHAIN_CREATED_BY_SAME_PERSON);
            }else{
                //查看公开的和自己创建的
                queryWrapper.nested(
                        qw->qw.eq(QuestionBankPO::getPublicRange, StaticFinalValue.PUBLIC)
                                .or()
                                .eq(QuestionBankPO::getCreatePerson,account).eq(QuestionBankPO::getPublicRange,StaticFinalValue.NOT_PUBLIC)

                );
            }
        }
        //belongFolderId不为空则进行文件夹限制；为空表示查询全部，无需加文件夹限制
        if (ObjectUtils.isNotEmpty(belongFolderId)){
            queryWrapper.like(QuestionBankPO::getBelongFolderFullId,belongFolderId);
        }
        //搜索条件过滤
        if(ObjectUtils.isNotEmpty(searchParam)){
            if (ObjectUtils.isNotEmpty(searchParam.getSearchValue())){
                queryWrapper.like(QuestionBankPO::getBankName,searchParam.getSearchValue());
            }
            //创建时间过滤
            if(ObjectUtils.isNotEmpty(searchParam.getStartTime())){
                queryWrapper.between(QuestionBankPO::getCreateTime,searchParam.getStartTime(),searchParam.getEndTime());
            }
        }

        queryWrapper.orderByDesc(QuestionBankPO::getCreateTime);
        Page<QuestionBankPO> page = new Page<>(currentPage,pageSize);
        return questionBankMapper.selectPage(page, queryWrapper);
//        return questionBankMapper.selectList(queryWrapper);
    }


//    @Transactional
    public int questionBankUpdate(QuestionBankPO questionBankPO){
        return questionBankMapper.updateById(questionBankPO);
    }




//    public int questionBankDelete(String id){
//        return questionBankMapper.deleteById(id);
//    }

    @Transactional
    public int questionBankDelete(List<String> questionBankIds,String account,Integer userType){
        LambdaQueryWrapper<QuestionBankPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //不是超管不能删除其他人的题库
        if(userType.equals(StaticFinalValue.TEACHER)){
            lambdaQueryWrapper.eq(QuestionBankPO::getCreatePerson,account);
        }
        //先筛选出能删除的题库
        lambdaQueryWrapper.in(QuestionBankPO::getId,questionBankIds);
        List<QuestionBankPO> questionBankPOS = questionBankMapper.selectList(lambdaQueryWrapper);
        List<String> canRemoveIds = questionBankPOS.stream().map(QuestionBankPO::getId).collect(Collectors.toList());

        //从试题表中删除关联的试题
        LambdaQueryWrapper<QuestionPO> questionPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionPOLambdaQueryWrapper.in(QuestionPO::getBelongQuestionBankId,canRemoveIds);
        questionMapper.delete(questionPOLambdaQueryWrapper);

        return questionBankMapper.deleteBatchIds(canRemoveIds);
//        return questionBankMapper.deleteBatchIds(ids);
    }


    public int questionBankMove(List<String> questionBankIds,QuestionBankPO questionBankPO,String account,Integer userType){
        LambdaQueryWrapper<QuestionBankPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(userType.equals(StaticFinalValue.TEACHER)){
            lambdaQueryWrapper.eq(QuestionBankPO::getCreatePerson,account);
        }
        lambdaQueryWrapper.in(QuestionBankPO::getId,questionBankIds);
        return questionBankMapper.update(questionBankPO,lambdaQueryWrapper);
    }


    //添加试题成功后，更新题库各个试题数
    @Async
    public void updateQuestionTypeNum(String questionBankId){
        System.out.println("========更新题库试题数============");
        LambdaQueryWrapper<QuestionPO> questionPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        questionPOLambdaQueryWrapper.eq(QuestionPO::getBelongQuestionBankId,questionBankId);
        List<QuestionPO> questionPOS = questionMapper.selectList(questionPOLambdaQueryWrapper);
        Map<Integer, Long> questionTypeMap = questionPOS.stream().collect(Collectors.groupingBy(QuestionPO::getQuestionType, Collectors.counting()));

        QuestionBankPO questionbankPO = new QuestionBankPO();
        questionbankPO.setId(questionBankId);
        Long radioCount = questionTypeMap.get(StaticFinalValue.RADIO);
        if(ObjectUtils.isNotEmpty(radioCount)){
            questionbankPO.setRadioCount((int)radioCount.longValue());
        }
        Long multipleChoiceCount = questionTypeMap.get(StaticFinalValue.MULTIPLE);
        if(ObjectUtils.isNotEmpty(multipleChoiceCount)){
            questionbankPO.setMultipleChoiceCount((int)multipleChoiceCount.longValue());
        }
        Long trueOrFalseCount = questionTypeMap.get(StaticFinalValue.TRUE_OR_FALSE);
        if(ObjectUtils.isNotEmpty(trueOrFalseCount)){
            questionbankPO.setTrueOrFalseCount((int)trueOrFalseCount.longValue());
        }
        Long fillCount = questionTypeMap.get(StaticFinalValue.FILL);
        if(ObjectUtils.isNotEmpty(fillCount)){
            questionbankPO.setFillCount((int)fillCount.longValue());
        }
        Long questionCount = questionTypeMap.get(StaticFinalValue.QUESTION);
        if(ObjectUtils.isNotEmpty(questionCount)){
            questionbankPO.setQuestionCount((int)questionCount.longValue());
        }
        if(ObjectUtils.isNotEmpty(questionPOS)){
            questionbankPO.setTotalCount(questionPOS.size());
        }
//        Integer radioCount = ObjectUtils.isEmpty(questionTypeMap.get(1))?0:(int)questionTypeMap.get(1).longValue();
//        Integer multipleChoiceCount = ObjectUtils.isEmpty(questionTypeMap.get(2))?0:(int)questionTypeMap.get(2).longValue();
//        Integer trueOrFalseCount = ObjectUtils.isEmpty(questionTypeMap.get(3))?0:(int)questionTypeMap.get(3).longValue();
//        Integer fillCount = ObjectUtils.isEmpty(questionTypeMap.get(4))?0:(int)questionTypeMap.get(4).longValue();
//        Integer questionCount = ObjectUtils.isEmpty(questionTypeMap.get(5))?0:(int)questionTypeMap.get(5).longValue();
//        questionbankPO.setRadioCount(radioCount);
//        questionbankPO.setMultipleChoiceCount(multipleChoiceCount);
//        questionbankPO.setTrueOrFalseCount(trueOrFalseCount);
//        questionbankPO.setFillCount(fillCount);
//        questionbankPO.setQuestionCount(questionCount);

        questionBankMapper.updateById(questionbankPO);
    }
}
